//
//  NextViewController.m
//  stagesetptcture
//
//  Created by bigarto-mac1 on 2018/1/31.
//  Copyright © 2018年 bigarto-mac1. All rights reserved.
//

#define kScreen_Height [UIScreen mainScreen].bounds.size.height
#define kScreen_Width [UIScreen mainScreen].bounds.size.width

#define MaxSCale 2.0  //最大缩放比例
#define MinScale 0.1  //最小缩放比例

#import "NextViewController.h"
#import "UIView+Frame.h"
#import "UIImage+Common.h"

@interface NextViewController ()

//背景图
@property (nonatomic, strong) UIImageView *backgroundImageView;
//画
@property (nonatomic, strong) UIImageView *artImageView;
//调整留白
@property (nonatomic, strong) UISlider *spaceSlider;
//画的整体缩放比例
@property (nonatomic, assign) CGFloat totalScale;
//最大留白
@property (nonatomic, assign) CGFloat maxSpace;
//合成图片的宽
@property (nonatomic, assign) CGFloat syntheticImageWidth;
//合成图片的高
@property (nonatomic, assign) CGFloat syntheticImageHeight;

@end

@implementation NextViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor lightGrayColor];
    self.totalScale = 1.0;
    self.maxSpace = 2000;
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"完成" style:UIBarButtonItemStylePlain target:self action:@selector(completeSyntheticPicture)];
    
    if (!_backgroundImageView) {
        _backgroundImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 64, kScreen_Width, kScreen_Width)];
        _backgroundImageView.contentMode = UIViewContentModeScaleAspectFit;
        _backgroundImageView.image = [UIImage imageNamed:@"background.jpg"];
        _backgroundImageView.layer.masksToBounds = YES;
        [self.view addSubview:_backgroundImageView];
    }
    _syntheticImageWidth = _backgroundImageView.image.size.width * 2;
    _syntheticImageHeight = _backgroundImageView.image.size.height * 2;
    
    CGFloat width = kScreen_Width / 2;
    CGFloat height = width * (_image.size.height / _image.size.width);
    if (!_artImageView) {
        _artImageView = [[UIImageView alloc] initWithFrame:CGRectMake((kScreen_Width - width) / 2, 64 + 40, width, height)];
        _artImageView.contentMode = UIViewContentModeScaleAspectFit;
        _artImageView.image = [self syntheticArtAndBox:_image];
        _artImageView.userInteractionEnabled = YES;
        _artImageView.multipleTouchEnabled = YES;
        [_artImageView addGestureRecognizer:[[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchView:)]];
        [_artImageView addGestureRecognizer:[[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panView:)]];
        [self.view addSubview:_artImageView];
        //阴影颜色
        _artImageView.layer.shadowColor = [UIColor blackColor].CGColor;
        //阴影偏移 默认(0, -3)
        _artImageView.layer.shadowOffset = CGSizeMake(3, 3);
        //阴影透明度
        _artImageView.layer.shadowOpacity = 0.8;
        //阴影半径
        _artImageView.layer.shadowRadius = 3;
    }
    if (!_spaceSlider) {
        CGFloat sliderWidth = 200;
        CGFloat sliderHeight = 20;
        _spaceSlider = [[UISlider alloc] initWithFrame:CGRectMake((kScreen_Width - sliderWidth) / 2, _backgroundImageView.bottom + 40, sliderWidth, sliderHeight)];
        _spaceSlider.maximumValue = _maxSpace;
        _spaceSlider.minimumValue = 0;
        _spaceSlider.value = 0;
        //是否为滑动时改变value
        _spaceSlider.continuous = NO;
        [_spaceSlider addTarget:self action:@selector(dragSlider:) forControlEvents:UIControlEventValueChanged];
        [self.view addSubview:_spaceSlider];
    }
}
//捏合
- (void)pinchView:(UIPinchGestureRecognizer *)pinchGestureRecognizer {
    if (pinchGestureRecognizer.scale > 1.0) {
        if (self.totalScale > MaxSCale) return;
    }
    if (pinchGestureRecognizer.scale < 1.0) {
        if (self.totalScale < MinScale) return;
    }
    _artImageView.transform = CGAffineTransformScale(_artImageView.transform, pinchGestureRecognizer.scale, pinchGestureRecognizer.scale);
    self.totalScale *= pinchGestureRecognizer.scale;
    pinchGestureRecognizer.scale = 1.0;
}
//拖拽
- (void)panView:(UIPanGestureRecognizer *)panGestureRecognizer {
    CGPoint translation = [panGestureRecognizer translationInView:self.view];
    CGPoint center = _artImageView.center;
    center.x += translation.x;
    center.y += translation.y;
    _artImageView.center = center;
    [panGestureRecognizer setTranslation:CGPointZero inView:self.view];
}
//改变画与画框之间的留白
- (void)dragSlider:(UISlider *)slider {
    _artImageView.image = [self getSyntheticImageWithImage:_image spaceValue:slider.value];
}
//先将画和画框合到一起
- (UIImage *)syntheticArtAndBox:(UIImage *)image {
    return [self getSyntheticImageWithImage:image spaceValue:0];
}
//画框和画合成的封装
- (UIImage *)getSyntheticImageWithImage:(UIImage *)image spaceValue:(CGFloat)spaceValue {
    UIImage *topBoxImage = [UIImage imageNamed:@"allegrobronze_b"];
    //调整画框和画整体的清晰度  越大清晰
    CGFloat scale = 5;
    //画框整体的宽高
    CGFloat realBoxWidth = topBoxImage.size.width * scale;
    CGFloat realBoxHeight = topBoxImage.size.height * scale;
    //框单独的宽度  60为画框的框的原始宽度
    CGFloat boxWidth = 60 * scale;
    //图片宽高
    CGFloat imageWidth = realBoxWidth - 2 * boxWidth;
    CGFloat imageHeight = imageWidth / (image.size.width / image.size.height);
    //开启上下文将画和画框放到一起
    UIGraphicsBeginImageContext(CGSizeMake(realBoxWidth, imageHeight + 2 * boxWidth));
    [[UIImage imageWithColor:[UIColor whiteColor]] drawInRect:CGRectMake(0, 0, realBoxWidth, realBoxHeight)];
//    [image drawInRect:CGRectMake(boxWidth, boxWidth, imageWidth, imageHeight)];
    CGFloat spaceWidth = spaceValue * 0.5;
    CGFloat spaceHeight = spaceValue * (imageHeight / imageWidth) * 0.5;
    [_image drawInRect:CGRectMake(boxWidth + spaceWidth, boxWidth + spaceHeight, imageWidth - spaceWidth * 2, imageHeight - spaceHeight * 2)];
    [topBoxImage drawInRect:CGRectMake(0, 0, realBoxWidth, realBoxHeight)];
    UIImage *bottomBoxImage = [UIImage imageNamed:@"allegrobronze_c"];
    [bottomBoxImage drawInRect:CGRectMake(0, imageHeight + boxWidth, realBoxWidth, boxWidth)];
    UIImage *syntheticImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return syntheticImage;
}
//合成
- (void)completeSyntheticPicture {
    //画布大小  越大合成的图片质量越好
    
//    CGFloat scale = _syntheticImageWidth / _backgroundImageView.width;
////    UIGraphicsBeginImageContext(CGSizeMake(_syntheticImageWidth, _syntheticImageHeight));
//    UIGraphicsBeginImageContextWithOptions(CGSizeMake(_syntheticImageWidth, _syntheticImageHeight), NO, [UIScreen mainScreen].scale);
//    [_backgroundImageView.image drawInRect:CGRectMake(0, 0, _syntheticImageWidth, _syntheticImageHeight)];
//    //得到画在画框坐标系中的位置
//    CGRect artFrame = [self.view convertRect:_artImageView.frame toView:_backgroundImageView];
//    //放大
//    CGRect artTargetFrame = CGRectMake(artFrame.origin.x * scale, artFrame.origin.y * scale, artFrame.size.width * scale, artFrame.size.height * scale);
//    [_artImageView.image drawInRect:artTargetFrame];
//    UIImage *syntheticImage = UIGraphicsGetImageFromCurrentImageContext();
//    UIGraphicsEndImageContext();
//    if (_syntheticSuccessBlock) {
//        _syntheticSuccessBlock(syntheticImage);
//    }
//    [self.navigationController popViewControllerAnimated:YES];
    
    
    CGFloat canvasSize = 960;
    CGFloat scale = canvasSize / _backgroundImageView.width;
    UIGraphicsBeginImageContext(CGSizeMake(canvasSize, canvasSize));
    [_backgroundImageView.image drawInRect:CGRectMake(0, 0, canvasSize, canvasSize)];
    //得到画在画框坐标系中的位置
    CGRect artFrame = [self.view convertRect:_artImageView.frame toView:_backgroundImageView];
    //放大
    CGRect artTargetFrame = CGRectMake(artFrame.origin.x * scale, artFrame.origin.y * scale, artFrame.size.width * scale, artFrame.size.height * scale);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSaveGState(context);
    //带颜色的阴影
    CGContextSetShadowWithColor(context, CGSizeMake(15, 15), 25, [[UIColor blackColor] CGColor]);
//    CGContextSetShadow(context, CGSizeMake(15, 15), 25);
    //3.添加矩形
    CGContextAddRect(context, CGRectMake(artTargetFrame.origin.x, artTargetFrame.origin.y, artTargetFrame.size.width, artTargetFrame.size.height));
    //4.设置绘图属性
//    [[UIColor redColor] setFill];      //填充色
//    [[UIColor blackColor] setStroke];  //描边
    //5.画矩形
    CGContextDrawPath(context, kCGPathEOFillStroke);
    //恢复旧的绘图上下文
    CGContextRestoreGState(context);
    
    [_artImageView.image drawInRect:artTargetFrame];
    UIImage *syntheticImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    if (_syntheticSuccessBlock) {
        _syntheticSuccessBlock(syntheticImage);
    }
    [self.navigationController popViewControllerAnimated:YES];

    //有阴影效果的合成 但是像素不够
//    CGRect artFrame = [self.view convertRect:_artImageView.frame toView:_backgroundImageView];
//    _artImageView.frame = artFrame;
//    [_backgroundImageView addSubview:_artImageView];
//    UIImage *syntheticImage = [self imageFromView:_backgroundImageView];
//    if (_syntheticSuccessBlock) {
//        _syntheticSuccessBlock(syntheticImage);
//    }
//    [self.navigationController popViewControllerAnimated:YES];
}

/** 根据view生成图片 */
- (UIImage *)imageFromView:(UIImageView *)theView {
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(theView.frame.size, YES, [UIScreen mainScreen].scale);
    [theView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return theImage;
}

@end
